using System.ComponentModel;
using System.Windows.Forms;
using BizTalk.BuildGenerator.UI.Navigation;
using System;

namespace BizTalk.BuildGenerator.UI.UserControls
{
    public partial class GenerateFilesControl : UserControl, IWizardControl
    {
        public delegate void GenerationCompleteDelegate();

        public event GenerationCompleteDelegate GenerationComplete;


        private GenerationArgs _Args;


        public GenerateFilesControl()
        {
            InitializeComponent();
        }

        public void RegisterArgs(GenerationArgs args)
        {
            _Args = args;
        }

        #region IWizardControl Members

        public MoveNextResult MoveNext()
        {
            backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += new DoWorkEventHandler(this.backgroundWorker_DoWork);
            backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(this.backgroundWorker_ProgressChanged);
            backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.backgroundWorker_RunWorkerCompleted);
            backgroundWorker.WorkerReportsProgress = true;
            backgroundWorker.RunWorkerAsync(_Args);
            MoveNextResult result = new MoveNextResult();
            result.CanMoveNext = false;
            return result;
        }

        #endregion

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Type providerType = Type.GetType(this._Args.GenerationProvider, false, true);
            if (providerType == null)
                throw new ApplicationException("Invalid Generation Provider");

            IBuildProvider buildProvider = (IBuildProvider)Activator.CreateInstance(providerType);
            buildProvider.Update += new BuildGenerator.BuildProcessUpdate(UpdateProgress);
            buildProvider.CreateBuild(this._Args);            
        }

        private void UpdateProgress(int percentageComplete)
        {
            try
            {
                backgroundWorker.ReportProgress(percentageComplete);
            }
            catch
            { }
        }


        private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            StatusProgressBar.Value = e.ProgressPercentage;
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.ToString());
            }
            if (GenerationComplete != null)
                GenerationComplete();
        }
    }
}